package com.mxx.common.data.transaction;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.io.Closeable;

public class TransactionManual implements Closeable {
    private PlatformTransactionManager transactionManager;
    private TransactionStatus transactionStatus;
    private boolean stat = false;

    public TransactionManual(PlatformTransactionManager platformTransactionManager) {
        this.transactionManager = platformTransactionManager;
    }


    public TransactionManual begin() {
        if (transactionStatus == null) {
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            this.transactionStatus = transactionManager.getTransaction(def);
        }
        return this;
    }

    public void commit() {
        this.stat = true;
        this.exec();
    }

    public void rollback() {
        this.stat = false;
        this.exec();
    }

    public boolean rollback(boolean state) {
        if (state) {
            this.stat = false;
            this.exec();
        }
        return state;
    }

    public void exec() {
        if (transactionStatus != null) {
            if (stat) {
                transactionManager.commit(transactionStatus);
            } else {
                transactionManager.rollback(transactionStatus);
            }
            this.transactionManager = null;
            this.transactionStatus = null;
        }
    }

    @Override
    public void close() {
        this.exec();
    }
}
